package cn.ycc1.boot3mvc.aspect;

import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.condition.RequestConditionHolder;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author ycc
 * @date 2024/3/17
 */
@Component
@Aspect
@Slf4j
public class CcLogAspect {
    @Pointcut("@annotation(cn.ycc1.boot3mvc.annotation.CcLog)")
    public void ccLogAspect(){}

    @Before("ccLogAspect()")
    public void beforeCcLog(JoinPoint joinPoint) {
        log.info("aspect coming");
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        String methodName = joinPoint.getSignature().getName();
        log.info("=============================== Method " + methodName + " () begin =================================");
        // 执行时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = new Date();
        String time = sdf.format(d);
        log.info("Time: " + time);
        log.info("URL: " + request.getRequestURL()); // 请求url
        log.info("HTTP Method: " + request.getMethod()); // 请求方法
        log.info("Class Method: " + joinPoint.getSignature().getDeclaringTypeName() + "." + methodName);
        log.info("IP: " + request.getRemoteHost());
        log.info("Request Args: " + JSON.toJSONString(joinPoint.getArgs()));
        log.info("Executing Controller ...");
    }

    @After("ccLogAspect()")
    public void afterCcLog(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        log.info("========================= Method " + methodName + " () end =====================================");
    }
}
